<template>
  <div class="dashboard-container">

    <!-- 底部快捷操作 -->
<!--    <div class="quick-actions">-->
<!--      <h3 class="section-title">快捷操作</h3>-->
<!--      <el-row :gutter="20">-->
<!--        <el-col :span="4" v-for="action in quickActions" :key="action.name">-->
<!--          <div class="action-item" @click="handleQuickAction(action)">-->
<!--            <div class="action-icon" :style="{backgroundColor: action.color}">-->
<!--              <i :class="action.icon"></i>-->
<!--            </div>-->
<!--            <div class="action-name">{{ action.name }}</div>-->
<!--          </div>-->
<!--        </el-col>-->
<!--      </el-row>-->
<!--    </div>-->


    <!-- 顶部数据概览 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card inventory-card">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-box"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">所有货物总量</div>
                <div class="stat-value">{{ inventoryTotal }}<span class="unit">件</span></div>
                <div class="stat-trend">
                  <span :class="inventoryTrend >= 0 ? 'up' : 'down'">
                    <i :class="inventoryTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(inventoryTrend) }}%
                  </span>
                  较上个月
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="6">
          <div class="stat-card turnover-card">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-refresh"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">仓库使用率</div>
                <div class="stat-value">{{ turnoverRate }}<span class="unit">%</span></div>
                <div class="stat-trend">
                  <span :class="turnoverTrend >= 0 ? 'up' : 'down'">
                    <i :class="turnoverTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(turnoverTrend) }}%
                  </span>
                  较上月
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="6">
          <div class="stat-card alert-card">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-warning-outline"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">库存总量</div>
                <div class="stat-value">{{ alertItems }}<span class="unit">件</span></div>
                <div class="stat-trend">
                  <span :class="alertTrend >= 0 ? 'up' : 'down'">
                    <i :class="alertTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(alertTrend) }}%
                  </span>
                  较上月
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <el-col :span="6">
          <div class="stat-card cost-card">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-money"></i>
              </div>
              <div class="stat-info">
                <div class="stat-title">仓库总收益</div>
                <div class="stat-value">{{ storageCost }}<span class="unit">元</span></div>
<!--                <div class="stat-trend">-->
<!--                  <span :class="costTrend >= 0 ? 'up' : 'down'">-->
<!--                    <i :class="costTrend >= 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>-->
<!--                    {{ Math.abs(costTrend) }}%-->
<!--                  </span>-->
<!--                  较上月-->
<!--                </div>-->
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 中间图表区域 -->
    <div class="chart-area">
      <el-row :gutter="20">
        <el-col :span="16">
          <div class="chart-card">
            <div class="chart-header">
              <h3>库存变化趋势</h3>
              <div class="chart-actions">
                <el-radio-group v-model="inventoryChartType" size="small">
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                  <el-radio-button label="quarter">季</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="chart-container">
              <div id="inventoryTrendChart" style="width: 100%; height: 300px;"></div>
            </div>
          </div>
        </el-col>

        <el-col :span="8">
          <div class="chart-card">
            <div class="chart-header">
              <h3>库存品类分布</h3>
            </div>
            <div class="chart-container">
              <div id="inventoryCategoryChart" style="width: 100%; height: 300px;"></div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt-20">
        <el-col :span="12">
          <div class="chart-card">
            <div class="chart-header">
              <h3>出入库统计</h3>
              <div class="chart-actions">
                <el-date-picker
                    v-model="inOutDateRange"
                    type="daterange"
                    align="right"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    size="small"
                    :picker-options="pickerOptions">
                </el-date-picker>
              </div>
            </div>
            <div class="chart-container">
              <div id="inOutChart" style="width: 100%; height: 300px;"></div>
            </div>
          </div>
        </el-col>

<!--        <el-col :span="12">-->
<!--          <div class="chart-card">-->
<!--            <div class="chart-header">-->
<!--              <h3>库存预警TOP10</h3>-->
<!--            </div>-->
<!--            <div class="chart-container">-->
<!--              <div id="alertChart" style="width: 100%; height: 300px;"></div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </el-col>-->
      </el-row>
    </div>


  </div>
</template>

<script>
import * as echarts from 'echarts';
import request from "@/utils/request";

export default {
  name: 'Dashboard',
  data() {
    return {
      // 顶部数据概览
      inventoryTotal: '',
      inventoryTrend: '',
      turnoverRate: '',
      turnoverTrend: '',
      alertItems: '',
      alertTrend: '',
      storageCost: 45.8,
      costTrend: -1.2,

      // 图表相关
      inventoryChartType: 'month',
      inOutDateRange: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      // // 快捷操作
      // quickActions: [
      //   {name: '入库登记', icon: 'el-icon-circle-plus', color: '#3a7bd5', path: '/inbound'},
      //   {name: '出库登记', icon: 'el-icon-remove', color: '#00d2ff', path: '/outbound'},
      //   {name: '库存盘点', icon: 'el-icon-tickets', color: '#00b09b', path: '/inventory'},
      //   {name: '调拨管理', icon: 'el-icon-sort', color: '#ff7e5f', path: '/transfer'},
      //   {name: '预警设置', icon: 'el-icon-warning', color: '#f46b45', path: '/alert'},
      //   {name: '报表导出', icon: 'el-icon-download', color: '#a18cd1', path: '/report'}
      // ],

      // 图表实例
      inventoryTrendChart: null,
      inventoryCategoryChart: null,
      inOutChart: null,
      // alertChart: null
    }
  },
  mounted() {
    this.initCharts();
    this.fetchData();
    this.fetchWareData();
    this.fetchItemData();
    this.fetchCostData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.inventoryTrendChart) {
      this.inventoryTrendChart.dispose();
    }
    if (this.inventoryCategoryChart) {
      this.inventoryCategoryChart.dispose();
    }
    if (this.inOutChart) {
      this.inOutChart.dispose();
    }
    // if (this.alertChart) {
    //   this.alertChart.dispose();
    // }
  },
  methods: {
    fetchData() {
      request.get('/goods/getGoodsCount', {
      })
      .then(response => {
        // 这里模拟数据，实际项目中替换为API返回的数据
        this.inventoryTotal = response.data.data.inventoryTotal;
        this.inventoryTrend = Math.round(response.data.data.inventoryTrend * 100) / 100;  //保留两位小数
        console.log("增长率")
        console.log(this.inventoryTrend)
        this.updateCharts();
      }).catch(error => {
        console.error('获取仪表盘数据失败:', error);
      });
    },
    fetchWareData() {
      request.get('/warehouse/getWarehouseRate', {
      })
          .then(response => {
            this.turnoverRate = Math.round(response.data.data.turnoverRate * 100) ;
            this.turnoverTrend = Math.round(response.data.data.turnoverTrend * 100) / 100;  //保留两位小数
            console.log("使用率")
            console.log(this.turnoverRate)
            console.log("增长率")
            console.log(this.turnoverTrend)
            this.updateCharts();
          }).catch(error => {
        console.error('获取仪表盘数据失败:', error);
      });
    },
    fetchItemData() {
      request.get('/inOut/getAlertItems', {
      })
          .then(response => {
            // 这里模拟数据，实际项目中替换为API返回的数据
            this.alertItems = response.data.data.alertItems;
            this.alertTrend = Math.round(response.data.data.alertTrend * 100) / 100;  //保留两位小数
            console.log("库存总量增长率")
            console.log(this.alertTrend)
            this.updateCharts();
          }).catch(error => {
        console.error('获取仪表盘数据失败:', error);
      });
    },
    fetchCostData(){

    },
    initCharts() {
      this.inventoryTrendChart = echarts.init(document.getElementById('inventoryTrendChart'));
      this.inventoryCategoryChart = echarts.init(document.getElementById('inventoryCategoryChart'));
      this.inOutChart = echarts.init(document.getElementById('inOutChart'));
      // this.alertChart = echarts.init(document.getElementById('alertChart'));
      this.updateCharts();
    },

    updateCharts() {
      // 库存趋势图
      this.inventoryTrendChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['入库量', '出库量', '库存量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '入库量',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: [320, 332, 301, 334, 390, 330, 320],
            itemStyle: {
              color: '#3a7bd5'
            }
          },
          {
            name: '出库量',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: [220, 182, 191, 234, 290, 330, 310],
            itemStyle: {
              color: '#00d2ff'
            }
          },
          {
            name: '库存量',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: [1200, 1352, 1262, 1362, 1462, 1462, 1472],
            itemStyle: {
              color: '#00b09b'
            }
          }
        ]
      });

      // 库存品类分布图
      this.inventoryCategoryChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['电子产品', '日用品', '食品', '服装', '其他']
        },
        series: [
          {
            name: '库存品类',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              {value: 335, name: '电子产品', itemStyle: {color: '#3a7bd5'}},
              {value: 310, name: '日用品', itemStyle: {color: '#00d2ff'}},
              {value: 234, name: '食品', itemStyle: {color: '#00b09b'}},
              {value: 135, name: '服装', itemStyle: {color: '#ff7e5f'}},
              {value: 1548, name: '其他', itemStyle: {color: '#a18cd1'}}
            ]
          }
        ]
      });

      // 出入库统计图
      this.inOutChart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['入库', '出库', '库存']
        },
        xAxis: [
          {
            type: 'category',
            data: ['1日', '2日', '3日', '4日', '5日', '6日', '7日'],
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量',
            min: 0,
            max: 250,
            interval: 50,
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '库存',
            min: 0,
            max: 1500,
            interval: 300,
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '入库',
            type: 'bar',
            barWidth: '30%',
            data: [45, 47, 52, 60, 65, 70, 75],
            itemStyle: {
              color: '#3a7bd5'
            }
          },
          {
            name: '出库',
            type: 'bar',
            barWidth: '30%',
            data: [35, 42, 48, 55, 62, 68, 74],
            itemStyle: {
              color: '#00d2ff'
            }
          },
          {
            name: '库存',
            type: 'line',
            yAxisIndex: 1,
            data: [1200, 1212, 1216, 1221, 1224, 1226, 1227],
            itemStyle: {
              color: '#00b09b'
            }
          }
        ]
      });

      // 库存预警TOP10
    //   this.alertChart.setOption({
    //     tooltip: {
    //       trigger: 'axis',
    //       axisPointer: {
    //         type: 'shadow'
    //       }
    //     },
    //     grid: {
    //       left: '3%',
    //       right: '4%',
    //       bottom: '3%',
    //       containLabel: true
    //     },
    //     xAxis: {
    //       type: 'value',
    //       boundaryGap: [0, 0.01]
    //     },
    //     yAxis: {
    //       type: 'category',
    //       data: ['商品A', '商品B', '商品C', '商品D', '商品E', '商品F', '商品G', '商品H', '商品I', '商品J']
    //     },
    //     series: [
    //       {
    //         name: '当前库存',
    //         type: 'bar',
    //         data: [12, 15, 18, 21, 24, 27, 30, 33, 36, 39],
    //         itemStyle: {
    //           color: function (params) {
    //             // 根据库存量设置不同颜色
    //             const value = params.data;
    //             if (value < 15) {
    //               return '#f46b45'; // 红色预警
    //             } else if (value < 25) {
    //               return '#ff7e5f'; // 橙色预警
    //             } else {
    //               return '#a18cd1'; // 紫色正常
    //             }
    //           }
    //         },
    //         label: {
    //           show: true,
    //           position: 'right',
    //           formatter: function (params) {
    //             const minStock = [10, 12, 15, 18, 20, 22, 25, 28, 30, 32]; // 最小库存量
    //             const index = params.dataIndex;
    //             return `最低:${minStock[index]} 当前:${params.data}`;
    //           }
    //         }
    //       }
    //     ]
    //   });
    },

    handleResize() {
      if (this.inventoryTrendChart) {
        this.inventoryTrendChart.resize();
      }
      if (this.inventoryCategoryChart) {
        this.inventoryCategoryChart.resize();
      }
      if (this.inOutChart) {
        this.inOutChart.resize();
      }
      // if (this.alertChart) {
      //   this.alertChart.resize();
      // }
    },

    // handleQuickAction(action) {
    //   this.$router.push(action.path);
    // }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 80px);
}

/* 顶部数据概览卡片 */
.data-overview {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  height: 120px;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.inventory-card .stat-icon {
  background: linear-gradient(135deg, #3a7bd5, #00d2ff);
}

.turnover-card .stat-icon {
  background: linear-gradient(135deg, #00b09b, #96c93d);
}

.alert-card .stat-icon {
  background: linear-gradient(135deg, #f46b45, #eea849);
}

.cost-card .stat-icon {
  background: linear-gradient(135deg, #a18cd1, #fbc2eb);
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-value .unit {
  font-size: 14px;
  font-weight: normal;
  margin-left: 2px;
}

.stat-trend {
  font-size: 12px;
  color: #909399;
}

.stat-trend .up {
  color: #67c23a;
  margin-right: 5px;
}

.stat-trend .down {
  color: #f56c6c;
  margin-right: 5px;
}

/* 图表区域 */
.chart-area {
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.chart-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  height: 100%;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-header h3 {
  font-size: 16px;
  color: #303133;
  margin: 0;
}

.chart-container {
  width: 100%;
}


</style>